package co.edu.unal.satacredito.mediation;

import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import co.edu.unal.satacredito.database.administration.ejb.AdministrationDaoEJBLocal;
import co.edu.unal.satacredito.database.administration.exceptions.DAOException;
import co.edu.unal.satacredito.database.entity.Administrator;
import co.edu.unal.satacredito.infrastructure.dto.UserDTO;

/**
 * Session Bean implementation class UserEJB
 */
@Stateless
public class UserEJB implements UserEJBRemote, UserEJBLocal {

	@EJB
	private AdministrationDaoEJBLocal administrationDaoEJBLocal;

	public UserEJB() {
		
	}
	
	@Override
	public UserDTO getUserFromLoginService(String username, String password) {

		try {
			Administrator admin = administrationDaoEJBLocal.findByUser(username);
			if (admin.getPassword().equals(password)) {
				return new UserDTO(admin);
			}
			return null;
		} catch (DAOException e1) {
			return null;
		}
	}
	
	@Override
	public void create(UserDTO userDTO) throws Exception {
		try {
    		Administrator user = new Administrator();
    		user.setName(userDTO.getName());
    		user.setLastName(userDTO.getLastName());
    		user.setDocument(userDTO.getDocument());
    		user.setUser(userDTO.getUser());
    		user.setPassword(userDTO.getPassword());
			administrationDaoEJBLocal.createAdministrator(user);
		} catch (Exception e) {
			throw e;
		}
		
	}

	@Override
	public void edit(String id, UserDTO userDTO) throws Exception{
		try {
    		Administrator user = new Administrator(id);
    		user.setName(userDTO.getName());
    		user.setLastName(userDTO.getLastName());
    		user.setDocument(userDTO.getDocument());
    		user.setUser(userDTO.getUser());
    		user.setPassword(userDTO.getPassword());
			administrationDaoEJBLocal.editAdministrator(user);
		} catch (Exception e) {
			throw e;
		}
		
	}

	@Override
	public void delete(String id) throws Exception{
		try {
			administrationDaoEJBLocal.deleteAdministrador(id);
		} catch (Exception e) {
			throw e;
		}
	}
	
	@Override
    public UserDTO findUser(String p_user) throws Exception{
    	try {
    		Administrator user = administrationDaoEJBLocal.findByUser(p_user);
			UserDTO user_return = new UserDTO(user);
			return user_return;
			
		} catch (Exception e) {
			return null;
		}
    }
	
	@Override
	public List<UserDTO> findAllUsers() {
		try {
			List<Administrator> admins = administrationDaoEJBLocal
					.findAllUsers();

			List<UserDTO> usersDTO = new ArrayList<UserDTO>();

			for (Administrator administrator : admins) {
				usersDTO.add(new UserDTO(administrator));
			}

			return usersDTO;

		} catch (DAOException e) {
			return new ArrayList<UserDTO>();
		}
	}
}
